﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting.Channels;
using System.Collections;
using MSRI.SmsService;
using System.Runtime.Remoting;
using MSRI.ActiveSyncServices;
using MSRI.TCPServices;
using System.Runtime.Remoting.Channels.Ipc;
using System.Threading;
using System.Runtime.Serialization.Formatters;
using MSRI.DesktopAgent.CeRapi;
using System.Net;
using MSRI.HelperClasses;
using System.Net.Sockets;

namespace SimpleSMSServer
{
    public class Connector
    {
        TcpClientClass tcpClient;
        IDccMan objIDccMan;
        private int IsActiveSyncConnected;

        public Connector()
        {
            tcpClient = new TcpClientClass();
            //tcpClient.MessageReceived += new TcpClientClass.MessageReceivedDelegate(this.tcpClient_MessageReceived);
            //tcpClient.Disconnected += new TcpClientClass.DisconnectedDelegate(this.tcpClient_Disconnected);
            //tcpClient.Connected += new TcpClientClass.ConnectedDelegate(this.tcpClient_Connected);
            //tcpClient.SmsReceived += new TcpClientClass.SmsReceivedDelegate(this.tcpClient_SmsReceived);
            //tcpClient.DeliveryReportReceived += new TcpClientClass.DeliveryReportReceivedDelegate(this.tcpClient_DeliveryReportReceived);
            DccMan man = new DccMan();
            objIDccMan = man as IDccMan;
            DccManSink objDccManSink = new DccManSink();
            objDccManSink.Disconnect += new DccManSink.DisconnectHandler(objDccManSink_Disconnect);
            objDccManSink.ConnectedToIPaddress += new DccManSink.OnLogIpAddrHandler(objDccManSink_ConnectedToIPaddress);
            int AdviceReturn = 0;
            objIDccMan.Advise(objDccManSink, ref AdviceReturn);
        }

        public void SendMessage(String number, String Body)
        {
            SmsClass Message = new SmsClass(number, Body);
            this.tcpClient.SendMessage(Message.ToString());
        }

        private void objDccManSink_Active()
        {
        }

        private void objDccManSink_ConnectedToIPaddress(int dwIpAddr)
        {
            Interlocked.Exchange(ref this.IsActiveSyncConnected, 1);
            short tcpPort = HelperClass.GetTcpPort();
            if (tcpPort == -1)
            {
                //this.StatusUpdate("Smartphone client not found!!");
                ;
            }
            else
            {
                IPAddress ip = new IPAddress((long)dwIpAddr);
                this.tcpClient.InitTcpClientClass(ip, tcpPort);
                if (!this.tcpClient.Connect())
                {
                   // base.Invoke(new ReStartDelegate(this.ReStartTimer));
                    ;
                }
            }
        }

        private void objDccManSink_Disconnect()
        {
            Interlocked.Exchange(ref this.IsActiveSyncConnected, 0);
        }
    }
}
